﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

using Repositories;
using Domain;

namespace Services
{
	public class TopicService
	{
		TopicRepository topicRep;

		public TopicService()
		{
			topicRep = new TopicRepository();
		}

		public IList<Topic> getTopics(Int64 forumID)
		{
			return topicRep.getTopics(forumID);
		}

		public IList<Topic> getActiveTopicsNew(string username)
		{
			return topicRep.getActiveTopicsNew(username);
		}



		public Int64 createTopic(string title, string content, Int16 subforumID, string topicStarterName, string topicStarterID, string ipaddress, out string urlTitle)
		{
			topicRep = new TopicRepository();
			SqlConnection connection = null;
			SqlTransaction transaction = null;

			urlTitle = title.Replace("-", "");
			urlTitle = urlTitle.Replace(" ", "-");
			urlTitle = urlTitle.Replace("!", "");
			urlTitle = urlTitle.Replace("@", "");
			urlTitle = urlTitle.Replace("#", "");
			urlTitle = urlTitle.Replace("$", "");
			urlTitle = urlTitle.Replace("%", "");
			urlTitle = urlTitle.Replace("^", "");
			urlTitle = urlTitle.Replace("&", "");
			urlTitle = urlTitle.Replace("*", "");
			urlTitle = urlTitle.Replace("(", "");
			urlTitle = urlTitle.Replace(")", "");
			urlTitle = urlTitle.Replace("=", "");
			urlTitle = urlTitle.Replace("[", "");
			urlTitle = urlTitle.Replace("]", "");
			urlTitle = urlTitle.Replace("{", "");
			urlTitle = urlTitle.Replace("}", "");
			urlTitle = urlTitle.Replace("|", "");
			urlTitle = urlTitle.Replace("\\", "");
			urlTitle = urlTitle.Replace("/", "");
			urlTitle = urlTitle.Replace(";", "");
			urlTitle = urlTitle.Replace(":", "");
			urlTitle = urlTitle.Replace("\"", "");
			urlTitle = urlTitle.Replace("\'", "");
			urlTitle = urlTitle.Replace("<", "");
			urlTitle = urlTitle.Replace(">", "");

			urlTitle = urlTitle.Replace(",", "");
			urlTitle = urlTitle.Replace(".", "");
			urlTitle = urlTitle.Replace("?", "");
			urlTitle = urlTitle.Replace("~", "");
			urlTitle = urlTitle.Replace("`", "");

			int length = 0;
			if (urlTitle.Length > 255)
			{
				length = 255;
			}
			else
			{
				length = urlTitle.Length;
			}

			urlTitle = urlTitle.Substring(0, length);

			Int64 topicID = topicRep.createTopic(title, urlTitle, content, subforumID, topicStarterName, topicStarterID, ref connection, ref transaction);

			PostingService pServ = new PostingService();
			pServ.InsertPosting(content, topicID, topicStarterName, topicStarterID, ipaddress, connection, transaction);

			transaction.Commit();
			connection.Close();
			connection.Dispose();

			return topicID;
		}


		public string getTopicTitle(Int64 topicID)
		{
			return topicRep.getTopicTitle(topicID);
		}

	}
}
